package cn.snmp.mutual.uk.stack;

import java.io.*;

public class SnmpContextv2cPool extends SnmpContextPool implements SnmpContextv2cFace {
    private static final String version_id = "@(#)$Id: SnmpContextv2cPool.java,v 3.15 2009/03/05 13:27:41 birgita Exp $ Copyright Westhawk Ltd";

    public SnmpContextv2cPool(final String host, final int port) throws IOException {
        super(host, port, "Standard");
    }

    public SnmpContextv2cPool(final String host, final int port, final String typeSocket) throws IOException {
        super(host, port, typeSocket);
    }

    public SnmpContextv2cPool(final String host, final int port, final String comm, final String typeSocket) throws IOException {
        super(host, port, comm, null, typeSocket);
    }

    public SnmpContextv2cPool(final String host, final int port, final String comm, final String bindAddress, final String typeSocket) throws IOException {
        super(host, port, comm, bindAddress, typeSocket);
    }

    @Override
    public int getVersion() {
        return 1;
    }

    @Override
    protected SnmpContext getMatchingContext() throws IOException {
        SnmpContextPoolItem item = null;
        SnmpContextv2c newContext = null;
        final String hashKey = this.getHashKey();
        this.destroy();
        synchronized (SnmpContextv2cPool.contextPool) {
            int count = 0;
            if (SnmpContextv2cPool.contextPool.containsKey(hashKey)) {
                item = (SnmpContextPoolItem) SnmpContextv2cPool.contextPool.get(hashKey);
                newContext = (SnmpContextv2c) item.getContext();
                count = item.getCounter();
            } else {
                newContext = new SnmpContextv2c(this.hostname, this.hostPort, this.bindAddr, this.socketType);
                newContext.setCommunity(this.community);
                item = new SnmpContextPoolItem(newContext);
                SnmpContextv2cPool.contextPool.put(hashKey, item);
            }
            ++count;
            item.setCounter(count);
        }
        return newContext;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}
